package com.atghost.minio.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.GeneralDigest;

import java.util.Map;


/**
 * @author Admin
 */
@Slf4j
@Data
@AllArgsConstructor
@Builder
@NoArgsConstructor
public class ChunkUploadContext {
    private String id;
    private String fileName;
    private String uploadId;
    private String fileKey;
    private Integer chunkCount;
    private Integer chunkSize;
    private long uploadSize;
    private long expectSize;
    // 失效时间点
    private long expireTime;
    private String chunkDir;
    private String instanceId;
    private String digest;
    private String digestAlgorithm;
    // 下次要上传的分片
    private Integer nextChunkId;
    private GeneralDigest messageDigest;
    private Map<Integer, String> etags;
    private Boolean complete = false;
    public synchronized Integer update(long byteCount, Integer chunkId, Digest digest, String etag) {
        if (!nextChunkId.equals(chunkId)) {
            log.warn("存在并发上传, id={}, uploadId={}, fileKey={}, nextChunkId={}, chunkId={}",
                id, uploadId, fileKey, nextChunkId, chunkId);
            return nextChunkId;
        }
        this.uploadSize += byteCount;
        this.messageDigest = (GeneralDigest) digest;
        this.nextChunkId++;
        if (nextChunkId > chunkCount) {
            nextChunkId = -1;
        }
        this.etags.put(chunkId, etag);
        return nextChunkId;
    }

}
